<?php
/**
*@作者:MissZhang
*@邮箱:<787727147@qq.com>
*@创建时间:2021/7/3 上午9:21
*@说明:商品模型
*/
namespace app\common\model;


use think\facade\Db;
use think\Model;

class Goods extends Model
{
    protected $pk = "goods_id";
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    //修改format类型
    protected $dateFormat = "Y-m-d H:i:s";
    protected $type=[
        'market_price'   =>  'float',
        'goods_price'     =>  'float',
        'ship_price'     =>  'float',
        'seckill_start_time'     =>  'integer',
        'seckill_end_time'     =>  'integer',
        'seckill_price'     =>  'float',
        'store_count'    =>  'integer',
        'sort'    =>  'integer',
    ];
    public function getPkAttr() {
        return $this->pk;
    }
    public function goodsImages()
    {
        return $this->hasMany(GoodsImages::class, 'goods_id', 'goods_id');
    }
    public function store()
    {
        return $this->hasOne(Store::class, 'store_id', 'store_id');
    }
    //获取等级价格
    public function getDengjiPrice($level){
        $level_price=$this->level_price;
        if (empty($level_price)){
            return '0.00';
        }
        $price=$level_price["level{$level}"];
        return $price;
    }
    //获取商品价格 秒杀中 返回秒杀价 否则返回商品价格
    public function getPriceAttr($value,$data) {
        if ($this->is_seckill){
            return $this->seckill_price;
        }
        return $this->goods_price;
    }
    //判断是否秒杀中
    public function getIsSeckillAttr($value,$data) {
        if ($data['seckill_start_time']==0 || $data['seckill_end_time']==0){
            return false;
        }
        if (time()>=$data['seckill_start_time'] && time()<$data['seckill_end_time']){
            return true;
        }
        return false;
    }
    public function getTypeTextAttr($value,$data) {
        $types = [1=>'普通',2=>'升级'];
        return $types[$data['goods_type']];
    }
    public function getGoodsStateAttr($value,$data) {
        if (!in_array($data['is_on_sale'],[-1,-2])){
            return 1;
        }
        return 0;
    }
    public function getGoodsStateTextAttr($value,$data) {
        if (in_array($data['is_on_sale'],[-1,-2])){
            $types = [-3=>'审核通过',-2=>'审核失败',-1=>'待审核'];
            return $types[$data['is_on_sale']];
        }
        return '审核通过';
    }
    public function getCatId1TextAttr($value,$data) {
        if ($data['cat_id_1']){
            return GoodsCategory::where('id',$data['cat_id_1'])->value('name');
        }
        return '无';
    }
    public function getCatId2TextAttr($value,$data) {
        if ($data['cat_id_2']){
            return GoodsCategory::where('id',$data['cat_id_2'])->value('name');
        }
        return '无';
    }
    public function getCatId3TextAttr($value,$data) {
        if ($data['cat_id_3']){
            return GoodsCategory::where('id',$data['cat_id_3'])->value('name');
        }
        return '无';
    }
    public function getSaleTextAttr($value,$data) {
        if ($data['is_on_sale']==1){
            return '是';
        }
        return '否';
    }
    public function getRecommendTextAttr($value,$data) {
        if ($data['is_recommend']==1){
            return '是';
        }
        return '否';
    }
    /**
     * 计算运费
     * @param $goods_id jifen_goods表id
     * @param $address_id 地址表id
     * @param $goods_num 数量
     */
    public function get_ship_price($goods_id,$address_id,$goods_num=1){
        if (empty($address_id)){
            return 0;
        }
        $goods=$this->where('goods_id',$goods_id)->find();
        //包邮
        if ($goods['ship_id']==0){
            return 0;
        }
        //地址信息
        $add=Db::name('user_address')->where('address_id',$address_id)->find();
        //物流信息
        $ship=Shipping::where('id',$goods['ship_id'])->find();
        //包邮地区
        $area=$ship['area'];
        //省份&城市&地区 都必须要在包邮地区内
        if (in_array($add['pid'],$area) && in_array($add['cid'],$area) && in_array($add['did'],$area)){
            return 0;
        }
        if ($goods_num<=$ship['frist_num']){
            return $ship['frist_money'];
        }
        $num=$goods_num-$ship['frist_num'];
        $xishu=ceil($num/$ship['second_num']);
        return $ship['frist_money'] + ($xishu*$ship['second_money']);
    }
    /**
     * 获取排好序的分类列表
     * @param string $level  //需要获取第几级分类
     * @return mixed
     */
    function getSortCategory()
    {
        $categoryList = cache('categoryList');
        if($categoryList)
        {
            return $categoryList;
        }
        $categoryList =  Db::name("GoodsCategory")->cache(true)->column('id,name,parent_id,level');
        $nameList = array();
        foreach($categoryList as $k => $v)
        {
            $name = getFirstCharter($v['name']) .' '. $v['name']; // 前面加上拼音首字母
            $nameList[] = $v['name'] = $name;
            $categoryList[$k] = $v;
        }
        array_multisort($nameList,SORT_STRING,SORT_ASC,$categoryList);

        cache('categoryList',$categoryList);
        return $categoryList;
    }
    /**
     * 获取 规格的 笛卡尔积
     * @param $goods_id int 商品 id
     * @param $spec_arr array 笛卡尔积
     * @return string 返回表格字符串
     */
    public function getSpecInput($goods_id, $spec_arr,$user_levels=[])
    {
        // <input name="item[2_4_7][price]" value="100" /><input name="item[2_4_7][name]" value="蓝色_S_长袖" />
        /*$spec_arr = array(
            20 => array('7','8','9'),
            10=>array('1','2'),
            1 => array('3','4'),

        );  */
        // 排序
        foreach ($spec_arr as $k => $v)
        {
            $spec_arr_sort[$k] = count($v);
        }
        asort($spec_arr_sort);
        foreach ($spec_arr_sort as $key =>$val)
        {
            $spec_arr2[$key] = $spec_arr[$key];
        }

        $clo_name = array_keys($spec_arr2);
        $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积
        $spec = Db::name('spec')->column('name','id'); // 规格表
        $specItem = Db::name('spec_item')->column('item,spec_id','id');//规格项
        $keySpecGoodsPrice = Db::name('spec_goods_price')->where('goods_id',$goods_id)->column('key_name,price,store_count,level_price','key');//规格项

        $str = "<table class='table table-bordered' id='spec_input_tab'>";
        $str .="<tr>";
        $str_fill = "<tr>";
        // 显示第一行的数据
        foreach ($clo_name as $v)
        {
            $str .=" <td><b>{$spec[$v]}</b></td>";
            $str_fill .=" <td><b></b></td>";
        }
        $str .="<td><b>商品价格</b></td>
               <td><b>库存</b></td>
             </tr>";
        if(count($spec_arr2) > 0){
            $str_fill .='<td><input id="item_price" class="table-input" value="0" onkeyup="this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)" onpaste="this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)"><button style="padding: 0 12px;margin-left: 5px" onclick="tianchong('."'item_price','item_level'".')" type="button" class="btn btn-theme">批量填充</button></td>
               <td><input id="item_store_count" class="table-input" value="0" onkeyup="this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)" onpaste="this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)"><button style="padding: 0 12px;margin-left: 5px" onclick="tianchong('."'item_store_count','item_store_count'".')" type="button" class="btn btn-theme">批量填充</button></td>
             </tr>';
            $str .= $str_fill;
        }
        // 显示第二行开始
        foreach ($spec_arr2 as $v)
        {
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $v2)
            {
                $str .="<td>{$specItem[$v2]['item']}</td>";
                $item_key_name[$v2] = $specItem[$v2]['item'];
            }
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);

            $keySpecGoodsPrice[$item_key]['price'] ? false : $keySpecGoodsPrice[$item_key]['price'] = 0; // 价格默认为0
            $keySpecGoodsPrice[$item_key]['store_count'] ? false : $keySpecGoodsPrice[$item_key]['store_count'] = 0; //库存默认为0
            $str .="<td class='item_level'>";
            if ($user_levels){
                $level_price=unserialize($keySpecGoodsPrice[$item_key]['level_price']);
                foreach ($user_levels as $user_level){
                    $price=$level_price?$level_price["level{$user_level['level_id']}"]:$keySpecGoodsPrice[$item_key]['price'];
                    $level_id=$user_level['level_id'];
                    $str .="<input class='table-input' value='$price' placeholder='请输入{$user_level['name']}价格' name='item[$item_key][level{$level_id}]' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' />";
                }
            }else{
                $str .="<input class='table-input' name='item[$item_key][price]' value='{$keySpecGoodsPrice[$item_key]['price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' />";
            }
            $str .="</td>";
            $str .="<td class='item_store_count'><input class='table-input' name='item[$item_key][store_count]' value='{$keySpecGoodsPrice[$item_key]['store_count']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
            $str .= "<input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            $str .="<td></td>";
            $str .="</tr>";
        }
        $str .= "</table>";
        return $str;
    }
    public function afterSave($goods_id,$levelList=[]){
        // 商品货号
        $goods_sn = "CSMC".str_pad($goods_id,7,"0",STR_PAD_LEFT);
        Db::name('goods')->where("goods_id = $goods_id and goods_sn = ''")->save(array("goods_sn"=>$goods_sn)); // 根据条件更新记录
        // 商品图片相册  图册
        $goods_images = input('goods_images/a',[]);
        if(count($goods_images) > 0)
        {
            $goodsImagesArr = Db::name('goods_images')->where("goods_id",$goods_id)->column('image_url','img_id'); // 查出所有已经存在的图片
            // 删除图片
            foreach($goodsImagesArr as $key => $val)
            {
                if(!in_array($val, $goods_images)){
                    Db::name('goods_images')->where("img_id",$key)->delete();
                }
            }
            // 添加图片
            foreach($goods_images as $key => $val)
            {
                if($val == null)  continue;
                if(!in_array($val, $goodsImagesArr))
                {
                    $data = array('goods_id' => $goods_id,'image_url' => $val);
                    Db::name("goods_images")->insert($data);
                }
            }
        }else{
            Db::name('goods_images')->where("goods_id",$goods_id)->delete();
        }
        // 商品规格价格处理
        $goods_item = input('item/a');
        $item_img = input('item_img/a');
        $specStock = Db::name('spec_goods_price')->where('goods_id = '.$goods_id)->column('store_count','key');
        if ($goods_item) {
            $keyArr = '';//规格key数组
            foreach ($goods_item as $k => $v) {
                $keyArr .= $k.',';
                // 批量添加数据
                $v['price'] = trim($v['price']);
                $store_count = $v['store_count'] = trim($v['store_count']); // 记录商品总库存
                $v['sku'] = trim($v['sku']);
                if ($levelList){
                    $arr=[];
                    foreach ($levelList as $level){
                        $arr["level{$level['level_id']}"]=$v['level'.$level['level_id']];
                    }
                    $data = ['goods_id' => $goods_id, 'key' => $k, 'key_name' => $v['key_name'], 'level_price' => serialize($arr), 'store_count' => $v['store_count']];
                }else{
                    $data = ['goods_id' => $goods_id, 'key' => $k, 'key_name' => $v['key_name'], 'price' => $v['price'], 'store_count' => $v['store_count']];
                }
                if ($item_img) {
                    $spec_key_arr = explode('_', $k);
                    foreach ($item_img as $key => $val) {
                        if (in_array($key, $spec_key_arr)) {
                            $data['spec_img'] = $val;
                            break;
                        }
                    }
                }
                if (!empty($specStock[$k])) {
                    Db::name('spec_goods_price')->where(['goods_id' => $goods_id, 'key' => $k])->update($data);
                } else {
                    Db::name('spec_goods_price')->insert($data);
                }
            }
            if($keyArr){
                Db::name('spec_goods_price')->where('goods_id',$goods_id)->whereNotIn('key',$keyArr)->delete();
            }
            //处理下商品总库存 按照规格库存累加 如果没有规格就不处理
            $new_store_count=Db::name('spec_goods_price')->where('goods_id = '.$goods_id)->sum('store_count');
            if ($new_store_count){
                Db::name('goods')->where('goods_id',$goods_id)->update(['store_count'=>$new_store_count]);
            }
        }else{
            Db::name('spec_goods_price')->where('goods_id',$goods_id)->delete();
        }
        // 商品规格图片处理
        $item_img=input('item_img/a');
        if($item_img) {
            Db::name('spec_image')->where("goods_id = $goods_id")->delete(); // 把原来删除再重新插入
            foreach ($item_img as $key => $val)
            {
                Db::name('spec_image')->insert(['goods_id'=>$goods_id ,'spec_image_id'=>$key,'src'=>$val]);
            }
        }
    }
    //用户浏览记录
    public function add_visit_log($user_id,$goods){
        $record = Db::name('goods_visit')->where(array('user_id'=>$user_id,'goods_id'=>$goods['goods_id']))->find();
        if($record){
            Db::name('goods_visit')->where(array('user_id'=>$user_id,'goods_id'=>$goods['goods_id']))->save(['visittime'=>time()]);
        }else{
            $visit = array('user_id'=>$user_id,'goods_id'=>$goods['goods_id'],'visittime'=>time());
            Db::name('goods_visit')->insert($visit);
        }
    }
}
